package com.zzyweb.rentalcarsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzyweb.rentalcarsys.entity.Menu;
import com.zzyweb.rentalcarsys.entity.Role;
import com.zzyweb.rentalcarsys.entity.relationship.RoleAndMenu;
import com.zzyweb.rentalcarsys.entity.relationship.UserAndRole;
import com.zzyweb.rentalcarsys.mapper.MenuMapper;
import com.zzyweb.rentalcarsys.mapper.RoleMapper;
import com.zzyweb.rentalcarsys.mapper.RoleMenuMapper;
import com.zzyweb.rentalcarsys.mapper.UserRoleMapper;
import com.zzyweb.rentalcarsys.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhiyi
 * @date 10/9/25
 **/
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    MenuMapper menuMapper;

    @Autowired
    RoleMenuMapper roleMenuMapper;
    @Override
    public List<Role> getAll() {
        List<Role> roles = roleMapper.selectList(null);
        for (int i = 0; i <roles.size() ; i++) {
            Integer roleId = roles.get(i).getRoleId();
            List<Menu> menus = menuMapper.selectMenusByRole(roleId);
            List<Menu> menuTree = getMenuTree(menus);
            if (!menuTree.isEmpty()) {
                roles.get(i).setMenus(menuTree);
            }
        }
        return roles;
    }

    @Override
    public void addRole(Role role) {
        roleMapper.insert(role);
    }

    @Override
    public void modifyRole(Role role) {
        roleMapper.updateById(role);
    }

    @Override
    @Transactional
    public void deleteRole(Integer roleId) {
        QueryWrapper<UserAndRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        userRoleMapper.delete(queryWrapper);
        //删除角色 中间表中这一数据相关也要删除
        roleMapper.deleteById(roleId);
    }

    @Override
    public void modifyMenuOfRole(String menuIds, Integer roleId) {
        if (roleId == null) throw new RuntimeException("empty or null");
        if (menuIds.equals("0")) {
            QueryWrapper<RoleAndMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", roleId);
            roleMenuMapper.delete(queryWrapper);
            return;
        }
        String[] strArr = menuIds.split(",");
        QueryWrapper<RoleAndMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        roleMenuMapper.delete(queryWrapper);
        RoleAndMenu roleAndMenu = new RoleAndMenu();
        roleAndMenu.setRoleId(roleId);
        for (int i = 0; i < strArr.length ; i++) {
            roleAndMenu.setId(null);
            roleAndMenu.setMenuId(Integer.parseInt(strArr[i]));
            roleMenuMapper.insert(roleAndMenu);
        }
    }

    @Override
    public List<Role> getRoleOfUser(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }

    private List<Menu> getMenuTree(List<Menu> menuList) {
        //按照parentId进行分类
        Map<Integer, List<Menu>> parentMap= menuList.stream().collect(Collectors.groupingBy(Menu::getParentId));
        //找出根节点菜单
        List<Menu> rootMenus = menuList.stream().filter(menu -> menu.getParentId() == null || menu.getParentId().equals(0))
                .collect(Collectors.toList());
        rootMenus.forEach(menu -> attachChildren(menu,parentMap));
        return rootMenus;
    }

    private void attachChildren(Menu parent, Map<Integer, List<Menu>> parentMap) {
        List<Menu> children = parentMap.get(parent.getMenuId());
        if (children != null && !children.isEmpty()) {
            parent.setChildren(children);
            children.forEach(child -> attachChildren(child, parentMap));
        }
    }
}
